<template>
  <div class="wenda-page">
    <!-- 标题栏 -->
    <van-nav-bar
      :title="isFAQMode ? '常见问答' : '问答中心'"
      left-arrow
      @click-left="goBack"
      fixed
      placeholder
    />

    <!-- FAQ模式：纯常见问题显示 -->
    <div v-if="isFAQMode" class="faq-page">
      <div class="faq-list">
        <van-collapse v-model="activeNames" accordion>
          <van-collapse-item
            v-for="item in faqList"
            :key="item._id"
            :title="item.title"
            :name="item._id"
          >
            <div class="faq-content">
              {{ item.shortCut }}
            </div>
          </van-collapse-item>
        </van-collapse>
      </div>
    </div>

    <!-- 问答中心模式：侧边栏+内容 -->
    <div v-else class="wenda-container">
      <!-- 侧边导航栏 -->
      <van-sidebar
        v-model="activeKey"
        @change="onSidebarChange"
        class="sidebar"
      >
        <van-sidebar-item title="常见问题" />
        <van-sidebar-item title="更多问题" />
        <van-sidebar-item title="问题详情" />
      </van-sidebar>

      <!-- 内容区域 -->
      <div class="content">
        <!-- 常见问题 -->
        <div v-if="activeKey === 0" class="faq-section">
          <div class="section-title">常见问题</div>
          <van-collapse v-model="activeNames" accordion>
            <van-collapse-item
              v-for="item in faqList"
              :key="item._id"
              :title="item.title"
              :name="item._id"
            >
              <div class="faq-content">
                {{ item.shortCut }}
              </div>
            </van-collapse-item>
          </van-collapse>
        </div>

        <!-- 更多问题 -->
        <div v-else-if="activeKey === 1" class="more-section">
          <div class="section-title">更多问题</div>
          <van-list
            v-model:loading="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <van-cell
              v-for="item in moreList"
              :key="item._id"
              :title="item.title"
              @click="showDetail(item)"
              is-link
            />
          </van-list>

          <!-- 问题详情弹窗 -->
          <van-popup
            v-model:show="showDetailPopup"
            position="bottom"
            :style="{ height: '60%' }"
            round
          >
            <div class="detail-content">
              <div class="detail-header">
                <h3>{{ selectedQuestion?.title }}</h3>
                <van-icon name="cross" @click="closeDetail" />
              </div>
              <div class="detail-body">
                {{ selectedQuestion?.shortCut }}
              </div>
            </div>
          </van-popup>
        </div>

        <!-- 问题详情 -->
        <div v-else-if="activeKey === 2" class="detail-section">
          <div class="section-title">问题详情</div>

          <!-- 问题选择器 -->
          <div class="question-selector">
            <van-field
              v-model="selectedQuestionId"
              label="选择问题"
              placeholder="请输入问题ID或选择问题"
              readonly
              @click="showQuestionPicker = true"
            />
            <van-button
              type="primary"
              size="small"
              @click="loadQuestionDetail"
              :loading="detailLoading"
              :disabled="!selectedQuestionId"
            >
              查看详情
            </van-button>
          </div>

          <!-- 问题详情内容 -->
          <div v-if="questionDetail" class="question-detail-content">
            <van-card class="detail-card">
              <template #title>
                <div class="detail-title">{{ questionDetail.title }}</div>
              </template>
              <template #desc>
                <div class="detail-meta">
                  <span class="view-count"
                    >浏览量: {{ questionDetail.viewCount }}</span
                  >
                  <span class="author">作者: {{ questionDetail.author }}</span>
                  <span class="date">{{
                    formatDate(questionDetail.createdAt)
                  }}</span>
                </div>
              </template>
              <template #body>
                <div class="detail-description">
                  <h4>问题描述</h4>
                  <p>{{ questionDetail.description }}</p>
                </div>
                <div class="detail-shortcut">
                  <h4>简要回答</h4>
                  <p>{{ questionDetail.shortCut }}</p>
                </div>
              </template>
            </van-card>
          </div>

          <!-- 问题选择弹窗 -->
          <van-popup
            v-model:show="showQuestionPicker"
            position="bottom"
            :style="{ height: '50%' }"
            round
          >
            <div class="picker-content">
              <div class="picker-header">
                <h3>选择问题</h3>
                <van-icon name="cross" @click="showQuestionPicker = false" />
              </div>
              <div class="picker-body">
                <van-cell
                  v-for="item in allQuestions"
                  :key="item._id"
                  :title="item.title"
                  @click="selectQuestion(item)"
                  is-link
                />
              </div>
            </div>
          </van-popup>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  NavBar,
  Sidebar,
  SidebarItem,
  Collapse,
  CollapseItem,
  List,
  Cell,
  Popup,
  Icon,
  Toast,
  Field,
  Button,
  Card,
} from "vant";
import httpd from "../../utils/httpd.js";

const router = useRouter();
const route = useRoute();

// 判断是否为FAQ模式（通过路由参数或路径判断）
const isFAQMode = computed(() => {
  return route.path === "/faq" || route.query.mode === "faq";
});

const activeKey = ref(0); // 默认显示常见问题
const activeNames = ref([]);
const faqList = ref([]);
const moreList = ref([]);
const loading = ref(false);
const finished = ref(false);
const showDetailPopup = ref(false);
const selectedQuestion = ref(null);
const currentPage = ref(1);
const pageSize = 5;

// 问题详情相关
const selectedQuestionId = ref("");
const questionDetail = ref(null);
const detailLoading = ref(false);
const showQuestionPicker = ref(false);
const allQuestions = ref([]);

// 返回上一页
const goBack = () => {
  router.back();
};

// 侧边栏切换
const onSidebarChange = (index) => {
  activeKey.value = index;
  if (index === 1 && moreList.value.length === 0) {
    // 切换到更多问题时，如果还没有数据则加载
    loadMoreQuestions();
  } else if (index === 2 && allQuestions.value.length === 0) {
    // 切换到问题详情时，如果还没有数据则加载
    loadAllQuestions();
  }
};

// 获取常见问题数据
const getFAQList = async () => {
  try {
    const response = await httpd.get("/api/v1/company/company-faq");
    if (response.statusCode === 200) {
      faqList.value = response.data.list;
    } else {
      Toast.fail("获取常见问题失败");
    }
  } catch (error) {
    console.error("获取常见问题失败:", error);
    Toast.fail("网络错误，请稍后重试");
  }
};

// 加载更多问题
const loadMoreQuestions = async () => {
  try {
    const response = await httpd.get(
      `/api/v1/company/company-faq-list?page=${currentPage.value}&size=${pageSize}`
    );
    if (response.statusCode === 200) {
      const newData = response.data.list;
      moreList.value = [...moreList.value, ...newData];

      // 检查是否还有更多数据
      if (currentPage.value >= response.data.totalPage) {
        finished.value = true;
      }
      currentPage.value++;
    } else {
      Toast.fail("获取更多问题失败");
    }
  } catch (error) {
    console.error("获取更多问题失败:", error);
    Toast.fail("网络错误，请稍后重试");
  }
};

// 加载所有问题（用于问题选择器）
const loadAllQuestions = async () => {
  try {
    const response = await httpd.get("/api/v1/company/company-faq");
    if (response.statusCode === 200) {
      allQuestions.value = response.data.list;
    } else {
      Toast.fail("获取问题列表失败");
    }
  } catch (error) {
    console.error("获取问题列表失败:", error);
    Toast.fail("网络错误，请稍后重试");
  }
};

// 加载问题详情
const loadQuestionDetail = async () => {
  if (!selectedQuestionId.value) {
    Toast.fail("请先选择问题");
    return;
  }

  detailLoading.value = true;
  try {
    const response = await httpd.get(
      `/api/v1/company/company-faq-info?faqid=${selectedQuestionId.value}`
    );
    if (response.statusCode === 200) {
      questionDetail.value = response.data;
    } else {
      Toast.fail("获取问题详情失败");
    }
  } catch (error) {
    console.error("获取问题详情失败:", error);
    Toast.fail("网络错误，请稍后重试");
  } finally {
    detailLoading.value = false;
  }
};

// 选择问题
const selectQuestion = (item) => {
  selectedQuestionId.value = item._id;
  showQuestionPicker.value = false;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN");
};

// 列表加载更多
const onLoad = () => {
  loadMoreQuestions();
  loading.value = false;
};

// 显示问题详情
const showDetail = (item) => {
  selectedQuestion.value = item;
  showDetailPopup.value = true;
};

// 关闭详情弹窗
const closeDetail = () => {
  showDetailPopup.value = false;
  selectedQuestion.value = null;
};

onMounted(() => {
  getFAQList();
});
</script>

<style scoped lang="less">
.wenda-page {
  min-height: 100vh;
  background: #f7f8fa;
}

// FAQ模式样式（纯常见问题显示）
.faq-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.faq-list {
  padding: 16px;
}

.faq-content {
  padding: 12px 0;
  line-height: 1.6;
  color: #666;
  font-size: 14px;
}

// 问答中心模式样式（侧边栏+内容）
.wenda-container {
  display: flex;
  height: calc(100vh - 46px);
}

.sidebar {
  width: 100px;
  background: #fff;
  border-right: 1px solid #ebedf0;
}

.content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 16px;
  padding-left: 8px;
}

.faq-section {
  .faq-content {
    padding: 12px 0;
    line-height: 1.6;
    color: #666;
    font-size: 14px;
  }
}

.more-section {
  .van-cell {
    margin-bottom: 8px;
    border-radius: 8px;
    background: #fff;
  }
}

// 问题详情模块样式
.detail-section {
  .question-selector {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 20px;

    .van-field {
      flex: 1;
    }

    .van-button {
      flex-shrink: 0;
    }
  }

  .question-detail-content {
    .detail-card {
      background: #fff;
      border-radius: 8px;
      margin-bottom: 16px;
    }

    .detail-title {
      font-size: 18px;
      font-weight: 600;
      color: #323233;
      margin-bottom: 8px;
    }

    .detail-meta {
      display: flex;
      gap: 16px;
      font-size: 12px;
      color: #969799;
      margin-bottom: 12px;

      .view-count,
      .author,
      .date {
        display: flex;
        align-items: center;
      }
    }

    .detail-description,
    .detail-shortcut {
      margin-bottom: 16px;

      h4 {
        font-size: 16px;
        font-weight: 500;
        color: #323233;
        margin-bottom: 8px;
      }

      p {
        line-height: 1.6;
        color: #666;
        font-size: 14px;
        margin: 0;
      }
    }
  }
}

.picker-content {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebedf0;

  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #323233;
    margin: 0;
  }

  .van-icon {
    font-size: 20px;
    color: #969799;
    cursor: pointer;
  }
}

.picker-body {
  flex: 1;
  overflow-y: auto;
}

.detail-content {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebedf0;

  h3 {
    font-size: 18px;
    font-weight: 600;
    color: #323233;
    margin: 0;
  }

  .van-icon {
    font-size: 20px;
    color: #969799;
    cursor: pointer;
  }
}

.detail-body {
  flex: 1;
  line-height: 1.6;
  color: #666;
  font-size: 14px;
  overflow-y: auto;
}

// 深度样式
:deep(.van-collapse-item__title) {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

:deep(.van-collapse-item__content) {
  background: #fafafa;
  border-radius: 8px;
  margin: 8px 0;
}

:deep(.van-sidebar-item) {
  font-size: 14px;
}

:deep(.van-sidebar-item--selected) {
  background: #e8f5e8;
  color: #6fb06c;
}

:deep(.van-card) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
